package com.caul.demo.hadoop.mapreduce.attention;

import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * Created by BlueDream on 2018-04-08.
 */
public class BothAttentKey implements WritableComparable<BothAttentKey> {

  private String attentA;
  private String attentB;

  public void set(String attentA, String attentB) {
    if (attentA.compareTo(attentB) <= 0) {//排序写入
      this.attentA = attentA;
      this.attentB = attentB;
    } else {
      this.attentA = attentB;
      this.attentB = attentA;
    }
  }

  public String getAttentA() {
    return attentA;
  }

  public void setAttentA(String attentA) {
    this.attentA = attentA;
  }

  public String getAttentB() {
    return attentB;
  }

  public void setAttentB(String attentB) {
    this.attentB = attentB;
  }

  /**
   * 在MapTask阶段,sortAndSpill时候调用,用于排序
   *
   * @param o
   * @return
   */
  @Override
  public int compareTo(BothAttentKey o) {
    int flag = this.attentA.compareTo(o.getAttentA());
    if (flag == 0) {
      flag = this.attentB.compareTo(o.getAttentB());
    }
    return flag;
  }

  @Override
  public void write(DataOutput out) throws IOException {
    out.writeUTF(this.attentA);
    out.writeUTF(this.attentB);
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    this.attentA = in.readUTF();
    this.attentB = in.readUTF();
  }

  @Override
  public String toString() {
    return this.attentA + " And " + this.attentB;
  }

  @Override
  public int hashCode() {
    return this.attentA.hashCode() * this.attentB.hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof BothAttentKey)) {
      return false;
    }
    return compareTo((BothAttentKey) obj) == 0;
  }
}
